import cv2 as cv
from matplotlib import pyplot as plt


# 大津算法对于双峰和三峰灰度直方图的效果对比
image01 = cv.imread('/Users/apple/Desktop/data/apple.jpg', 0)
image02 = cv.imread('/Users/apple/Desktop/data/rice.jpeg', 0)


# 灰度直方图
# hist = cv.calcHist([image], [0], None, [256], [0, 256])
plt.hist(image01.ravel(), 256, [0, 256])
plt.hist(image02.ravel(), 256, [0, 256])


# 大津算法
ret, thImg01 = cv.threshold(image01, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
ret, thImg02 = cv.threshold(image02, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)


# 显示对比效果
images = [image01, 0, thImg01,
          image02, 0, thImg02]

titles = ['Apple Image','Histogram',"Otsu's Thresholding",
          'Rices Image','Histogram',"Otsu's Thresholding"]

for i in range(2):
    plt.subplot(2, 3, i*3+1), plt.imshow(images[i*3], 'gray')
    plt.title(titles[i * 3]), plt.xticks([]), plt.yticks([])
    plt.subplot(2, 3, i*3+2), plt.hist(images[i*3].ravel(), 256)
    plt.title(titles[i*3+1]), plt.xticks([]), plt.yticks([])
    plt.subplot(2, 3, i*3+3), plt.imshow(images[i*3+2], 'gray')
    plt.title(titles[i*3+2]), plt.xticks([]), plt.yticks([])

plt.show()
